package com.sdtele.tta.operation;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.User;
import com.sdtele.tta.models.VoteOperation;
import com.sdtele.tta.models.VoteOption;
import com.sdtele.tta.models.VoteTask;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationAddVoteTask extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");

		String title = jsonRequest.getJsonObject().get("title").getAsString();
		Timestamp createTime = new Timestamp(System.currentTimeMillis());
		int voteType=jsonRequest.getJsonObject().get("voteType").getAsInt();
		//可以不传
		VoteTask votetask = new VoteTask();
		if ((jsonRequest.getJsonObject().get("deadLine") != null)
				&& (!jsonRequest.getJsonObject().get("deadLine").getAsString().equals(""))) {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd" );
			java.util.Date ud = new java.util.Date();

			Date deadLine = new java.sql.Date(ud.getTime());
			try {
				deadLine = sdf1.parse(jsonRequest.getJsonObject().get("deadLine").getAsString());
			} catch (ParseException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			votetask.setDeadLine(new java.sql.Date(deadLine.getTime()));
		}		
		String completion = jsonRequest.getJsonObject().get("completion").getAsString();
		
		
		votetask.setOwnerId(curUser.getId());
		votetask.setTitle(title);
		votetask.setCreatetime(createTime);
		votetask.setVoteType(voteType);
		if(completion==null) {
			votetask.setCompletion("0/0");
		}else {
			votetask.setCompletion(completion);
		}
	
		Dac.getInstance().addVoteTask(votetask);

		VoteOperation voteOperation=new VoteOperation();
    	voteOperation.setVoteId(votetask.getId());
    	voteOperation.setUserId(curUser.getId());
    	voteOperation.setOperation(0);
    	voteOperation.setCompletion(0);
    	Dac.getInstance().addVoteOperation(voteOperation);
		
		VoteTask  voteTask=Dac.getInstance().getVoteTaskbyVoteid(votetask.getId());
		 Map<String,Object> voteMap=new  HashMap<String,Object> ();
		 voteMap.put("voteTask", voteTask);
		 User owner =Dac.getInstance().getUser(curUser.getId());
		 System.out.println(owner);
		 voteMap.put("owner", owner);
		
		 if (voteMap.size()>0) {
			jres.setStatus(0);
			jres.setMessage("添加投票成功");
			jres.setEntity(voteMap);
		} else {
			jres.setStatus(1);
			jres.setMessage("未知错误，添加投票任务失败");
		}
		return jres;
	}

}